// pages/terminal/chart/index.js
var app = getApp(), fetchApi = require("../../../../utils/httpPost.js")
const wxCharts = require("../../../../utils/wxcharts.js"), 
commonJs = require("../../../../component/common.js")
import Toast from '../../../../component/vant/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLoading:true,
    deviceNum:'',
    deviceId:0,
    categories:[],
    wenduData:[],
    isShowPop:false,
    nodeTempList:[],
    canvasImgLast:'',
    canvasImgResult:'',
    chooseRange:'',
    lastData:{},
    resultData:{},
    minDate: new Date(2023, 0, 1).getTime(),
    showCalendar:false,
    beginDate:'',
    endDate:'',
    dataCode:'',
    isShowResult:true,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options',options)
    this.data.deviceId = parseInt(options.id)
    this.data.deviceNum = options.num;
    this.setData({
      deviceNum:this.data.deviceNum,
    })
    if(options.code){
      this.data.dataCode = options.code;
      this.setData({
        dataCode: options.code
      })
    }
    if(this.data.dataCode == ''){
      this.onHttpInit();
    }else{
      this.onHttpInitByCode();
    }
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    that.setData({ isLoading: true})
    fetchApi.httpPost('/device/range/chart', {
      device_id:that.data.deviceId,
    }, function (res) {
      console.log("传感器设备列表数据", res)
      if (res.data.code == 0) {
        that.data.lastData = res.data.data.lastData;
        that.data.resultData = res.data.data.resultData;
        that.setData({
          lastData:  res.data.data.lastData,
          resultData:  res.data.data.resultData,
        })
        that.data.canvasImgLast = '';
        that.data.canvasImgResult = '';
        that.getLastRecordChart();
        that.getResultDataChart();
      }
      that.setData({  isLoading: false, loading: true, netWork: true,  })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  
  /**
   * 获取页面数据的 http请求
   */
  onHttpInitByCode: function () {
    var that = this
    that.setData({ isLoading: true})
    fetchApi.httpPost('/device/range/record/chart', {
      device_id:that.data.deviceId,
      data_code: that.data.dataCode,
    }, function (res) {
      console.log("传感器设备列表数据", res)
      if (res.data.code == 0) {
        that.data.lastData = res.data.data.lastData;
        that.setData({
          lastData:  res.data.data.lastData,
          isShowResult:false,
        })
        that.data.canvasImgLast = '';
        // that.data.canvasImgResult = '';
        that.getLastRecordChart();
        // that.getResultDataChart();
      }
      that.setData({  isLoading: false, loading: true, netWork: true,  })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
   getLastRecordChart:function(){
    var windowWidth = 320;
    var that = this
    try {
     var res = wx.getSystemInfoSync();
     windowWidth = res.windowWidth;
    } catch (e) {
     console.error('getSystemInfoSync failed!');
    }
    var times = that.data.lastData.times;
    var values = that.data.lastData.values;
    // console.log('times',times)
    // console.log('values',values)
    this.setData({
      dataCode: that.data.lastData.data_code
    })
    if(times!= undefined &&  times.length > 0){
      var yuelineChart = new wxCharts({ //当月用电折线图配置
        canvasId: 'yueEle_0',
        type: 'line',
        categories:times, //times X轴
        animation: true,
        series: [{
          name: '垂直高度(M)',
          data: values,
          format: function (val, name) {
            return val.toFixed(2) + 'M';
          }
        }, 
       ],
        xAxis: {
           //x轴旋转
          axisLabel: {
            interval: 0, //隔几项显示一个标签
            rotate: "45" //标签倾斜的角度，旋转的角度是-90到90度
          },
          format: function (val) {
            return val.toFixed(2) +'°';
          },
          disableGrid: true,
        },
        yAxis: {
          title: '垂直高度(M)',
          format: function (val) {
            return val.toFixed(2);
          },
          min: 0,
          // max:1
        },
        width: windowWidth,
        height: 200,
        dataLabel: false,
        dataPointShape: true,
        extra: {  lineStyle: 'curve'  }
      });
    }

    if(that.data.canvasImgLast == '') {
      setTimeout(function(){
        that.data.canvasImgLast = '';
        that.handleCanvarToImg(0)
      },2000)
    }
   },
   onChangeCalendar(){
    this.setData({
      showCalendar: !this.data.showCalendar
    })
   },
   formatDate(date) {
    date = new Date(date);
    var month = date.getMonth() + 1 < 10 ? '0'+(date.getMonth() + 1) :date.getMonth() + 1;
    var day = date.getDate() < 10 ? '0'+(date.getDate()) :date.getDate();
    return `${date.getFullYear()}-${month}-${day}`;
  },
   onConfirmCalendar(event){
    const [start, end] = event.detail;
    this.data.beginDate = this.formatDate(start);
    this.data.endDate = this.formatDate(end);
    this.setData({
      showCalendar: !this.data.showCalendar,
      chooseRange: `${this.formatDate(start)}~${this.formatDate(end)}`,
    });
    this.onHttpResultData();
   },
   
  /**
   * 获取页面数据的 http请求
   */
  onHttpResultData: function () {
    var that = this
    that.setData({ isLoading: true})
    fetchApi.httpPost('/device/range/result/chart', {
      device_id:that.data.deviceId,
      begin_date: that.data.beginDate,
      end_date: that.data.endDate,
    }, function (res) {
      console.log("传感器设备列表数据", res)
      if (res.data.code == 0) {
        that.data.resultData = res.data.data;
        that.setData({
          resultData:  res.data.data,
        })
        that.data.canvasImgResult = '';
        that.getResultDataChart();
      }
      that.setData({  isLoading: false, loading: true, netWork: true,  })
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    })
  },
   getResultDataChart:function(){
    var windowWidth = 320;
    var that = this
    try {
     var res = wx.getSystemInfoSync();
     windowWidth = res.windowWidth;
    } catch (e) {
     console.error('getSystemInfoSync failed!');
    }
    var times = that.data.resultData.times;
    var values = that.data.resultData.values;
    if(times!= undefined && times.length > 0){
      var yuelineChart = new wxCharts({ //当月用电折线图配置
        canvasId: 'yueEle_1',
        type: 'line',
        categories:times, //times X轴
        animation: true,
        series: [{
          name: '重量(吨)',
          data: values,
          format: function (val, name) {
            return val.toFixed(2) + 'M';
          }
        }, 
       ],
        xAxis: {
           //x轴旋转
          axisLabel: {
            interval: 0, //隔几项显示一个标签
            rotate: "45" //标签倾斜的角度，旋转的角度是-90到90度
          },
          format: function (val) {
            return val.toFixed(2) +'吨';
          },
          disableGrid: true,
        },
        yAxis: {
          title: '重量(吨)',
          format: function (val) {
            return val.toFixed(2);
          },
          min: 0,
          // max:1
        },
        width: windowWidth,
        height: 200,
        dataLabel: false,
        dataPointShape: true,
        extra: {  lineStyle: 'curve'  }
      });
    }

    if(that.data.canvasImgResult == '') {
      setTimeout(function(){
        that.data.canvasImgResult = '';
        that.handleCanvarToImg(1)
      },2000)
    }
   },
   // 需要让 弹窗等 出现在canvas上的事件
   handleCanvarToImg(index) {
     var that = this;
     var windowWidth = 320;
     try {
       var res = wx.getSystemInfoSync();
       windowWidth = res.windowWidth;
       var id = 'yueEle_' + index;
       wx.canvasToTempFilePath({
         x: 0,
         y: 0,
         width: windowWidth,
         height: 200,
         canvasId: id,
         complete: function(res) {
          //  console.log( "id", id)
          if(index == 0){
              that.data.lastData.canvasImg = res.tempFilePath
              that.data.lastData.canvasWidth = windowWidth
              that.data.lastData.canvasHeight = 200;
              that.data.canvasImgLast = res.tempFilePath;
              that.setData({ 
                canvasImgLast:that.data.canvasImgLast,
                lastData:  that.data.lastData
              });
          }else{
              that.data.resultData.canvasImg = res.tempFilePath
              that.data.resultData.canvasWidth = windowWidth
              that.data.resultData.canvasHeight = 200;
              that.data.canvasImgResult = res.tempFilePath;
              that.setData({ 
                canvasImgResult:that.data.canvasImgResult,
                resultData:  that.data.resultData
              });
          }
          //  that.handleCanvarToImg(0)
         }
       });
     } catch (e) {
       console.error('getSystemInfoSync failed!');
     }
   },
   canvasIdErrorCallback(e){
    console.log('canvasIdErrorCallback',e)
   },
   onCancle(){
     var that = this;
    this.setData({
      isShowPop : false,
      lastData: that.data.lastData
    })
   },
   onConfirm(event){
    var that = this;
    that.data.lastData.canvasImg = '';
    that.data.lastData.canvasWidth = 0
    that.data.lastData.canvasHeight = 0
    that.setData({ lastData:  that.data.lastData});

     console.log('onConfirm',event)
     const { detail, currentTarget } = event;
     const result = this.getResult(detail, currentTarget.dataset.type);
     console.log('result',result)
     console.log('detail',detail)
     var ss = commonJs.formatTimeSimple(new Date(detail));
     that.data.nowDate = ss;
     this.setData({
      nowDate:ss,
       currentDate: detail,
       isShowPop:false
     })
     this.onHttpInit();
   },
   touchHandler: function (e) { //当月用电触摸显示
    yuelineChart.showToolTip(e, { //showToolTip图表中展示数据详细内容
     background: '#7cb5ec',
     format: function (item, category) {
      return category + '日 ' + item.name + ':' + item.data
     }
    });
   },
})